﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Read.API.Application.Command.RegistrationCommand;
using MediatR;

namespace D.Medicalcare.Read.API.Application.Handler.RegistrationHandler
{
    /// <summary>
    /// 修改排班人数
    /// </summary>
    public class UpdateDockorNumHandler : IRequestHandler<UpdateDockorNumCommand, APIResult<object>>
    {
        private readonly IBaseRepository<DoctorScheduling> repository;
        private readonly IMapper mapper;
        private readonly ILogger<UpdateDockorNumHandler> logger;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="mapper"></param>
        public UpdateDockorNumHandler(IBaseRepository<DoctorScheduling> repository,IMapper mapper,ILogger<UpdateDockorNumHandler> logger)
        {
            this.repository = repository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<object>> Handle(UpdateDockorNumCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
          
            try
            {
                var entity = repository.GetAll().FirstOrDefault(x => x.DoctorId == request.DoctorId && x.Date == request.Date);
                if (entity != null)
                {
                    if (request.WTime==entity.MorningAdmissions)
                    {
                        entity.MorningNumberPatients = entity.MorningNumberPatients + 1;
                        entity.MorningNumberSources=  entity.MorningNumberSources - 1;
                    }
                    if (request.WTime == entity.AfternoonAdmissions)
                    {
                        entity.AfternoonNumberPatients = entity.AfternoonNumberPatients + 1;
                        entity.AfternoonNumberSources = entity.AfternoonNumberSources - 1;
                    }
                    var a=repository.Update(entity).Result;
                    result.Code = APIEnum.Success;
                    result.Msg = "修改成功";
                    result.Data = a;
                }
                else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "未找到对应的排班信息";
                    result.Data = 0;
                }

            }

            catch (Exception ex)
            {
                logger.LogError("修改排班人数异常"+ex.Message);
            }

            return Task.FromResult(result);


        }
    }
}
